package whu.o2o;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import whu.o2o.View.LoadDialog;
import whu.o2o.util.ConstantData;
import whu.o2o.util.ImeUtil;
import whu.o2o.util.Utils;
import whu.o2o.vo.PersonVO;

import whu.o2o.R;
import whu.o2o.connection.CommonHttpConnect;
import whu.o2o.connection.Params;







import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class RegisterActivity extends BaseActivity implements OnClickListener{
	private EditText et_phone;
	private EditText et_yzm;
	private EditText et_password;
	private EditText et_passwordconfig;

	private Button bt_hqyzm;
	private ImageButton ib_register_submit;
	private ImageButton ib_back;
	private Context mcontext;
	private String phone; 
	private String yzm; 
	private String password; 
	private String passwordconfig; 
	
	int mPositiveCount;
	int count = 60;
	private Handler codeHandler,commitHandler,mHandler;
	private String userid;
	private SharedPreferences.Editor editor;
	private String[] str;
	private SharedPreferences sp;
	private List<NameValuePair> plist;
	private PersonVO uservo;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);
		initialHandler();
		initView();
	}
	
	private void initView(){
		mcontext = this;
		et_phone = (EditText) findViewById(R.id.et_register_phone);
		et_yzm = (EditText) findViewById(R.id.et_register_yzm);
		et_password = (EditText) findViewById(R.id.et_register_password);
		et_passwordconfig = (EditText) findViewById(R.id.et_register_passwordconfig);

		bt_hqyzm = (Button) findViewById(R.id.bt_register_hqyzm);
		
		ib_back= (ImageButton) findViewById(R.id.ib_register_back);
		ib_register_submit= (ImageButton) findViewById(R.id.ib_register_submit);
		
		 sp = getSharedPreferences("info",Context.MODE_PRIVATE);
	     editor=sp.edit();
		plist=new ArrayList<NameValuePair>();
		uservo = new PersonVO();
		
		ib_register_submit.setOnClickListener(this);
		ib_back.setOnClickListener(this);
		bt_hqyzm.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent;

		switch (v.getId()) {
		case R.id.bt_register_hqyzm:
			phone = et_phone.getText().toString().trim();
			if(!TextUtils.isEmpty(phone)&&Utils.isMobileNO(phone)){
				validateEnable();
				requestCode();
			}else{
				ImeUtil.showToast(this, "请输入真实电话号码", 2000);
			}
			
		
			break;

		case R.id.ib_register_back:
			finish();
			break;
						
		case R.id.ib_register_submit:
		    if(checkDate())
			requestData();
			break;
		

		}
		
	}
	
	private void requestData() {
		int userId = mApplication.getUserId();
		plist.clear();
		plist.add(new BasicNameValuePair("xml",writeXml()));
		Params params = new Params();
	
		params.setUrl(ConstantData.Url.POST_REGISTER
					);
		params.setList(plist);
		params.setHandler(commitHandler);
		params.setRequestType(ConstantData.Data.POST_HTTP);
		params.setMsgCode(ConstantData.Data.GET_HTTP_RESULT_MSG_CODE);
		params.setActivity(this);

		params.setShowLoad(true);

		LoadDialog.showDailog(this);
		mApplication.getThreadPool().execute(new CommonHttpConnect(params));
	}
	
	private boolean checkDate(){
		boolean flag = true;
	    phone = et_phone.getText().toString().trim();
	    yzm = et_yzm.getText().toString().trim();
	    password = et_password.getText().toString().trim();
	    passwordconfig = et_passwordconfig.getText().toString().trim();

		
		if (TextUtils.isEmpty(phone) || !Utils.isMobileNO(phone)) {
			ImeUtil.showToast(this,"请输入真实的手机号" , 2000);
			return flag = false;
		}
		if (TextUtils.isEmpty(yzm) ) {
			ImeUtil.showToast(this,"请输入验证码" , 2000);
			return flag = false;
		}
		if (TextUtils.isEmpty(password) ) {
			ImeUtil.showToast(this,"请输入密码" , 2000);
			return flag = false;
		}
		if (TextUtils.isEmpty(passwordconfig) ) {
			ImeUtil.showToast(this,"请输入确认密码" , 2000);
			return flag = false;
		}
		
	
		return flag;
	}
	
	private void validateEnable() {
		count = 60;
		bt_hqyzm.setText("重新获取(" + count + ")");
		bt_hqyzm.setTextColor(getResources().getColor(R.color.littlegray));
		bt_hqyzm.setBackgroundColor(getResources().getColor(R.color.green));
		bt_hqyzm.setEnabled(false);
		mPositiveCount = count;
		mHandler.sendEmptyMessageDelayed(1, 1000);
	}
	

	
	
	
	private void requestCode(){
		
		

		Params params = new Params();
	
			params.setUrl(String.format(ConstantData.Url.GET_CODE,
					phone));
	
		params.setHandler(codeHandler);
		params.setRequestType(ConstantData.Data.GET_HTTP);
		params.setMsgCode(ConstantData.Data.GET_HTTP_RESULT_MSG_CODE);
		params.setActivity(this);
		params.setShowLoad(true);
	

		LoadDialog.showDailog(this);
		mApplication.getThreadPool().execute(new CommonHttpConnect(params));
		
	}
	
	private String writeXml(){
		
		StringBuffer xmLDOC = new StringBuffer();
		xmLDOC.append("<?xml version='1.0' encoding='utf-8'?>");
		xmLDOC.append("<Page Update='true'>");
		xmLDOC.append("<type>" + "2" + "</type>");
		xmLDOC.append("<userid>" + userid + "</userid>");
		xmLDOC.append("<mobile>" + phone + "</mobile>");
		xmLDOC.append("<vcode>" + yzm + "</vcode>");
		xmLDOC.append("<password>" + password + "</password>");
		xmLDOC.append("</Page>");
		return xmLDOC.toString();
		
	}

	private void initialHandler(){
		codeHandler=new Handler()
		{
			public void handleMessage(Message msg)
			{
				super.handleMessage(msg);
				LoadDialog.closeDialog();
				if(msg.obj!=null && !msg.obj.toString().equals("")){
					String s=msg.obj.toString();
					
					try {
						str = s.split(",");
						if (str[0].equals("true_new")) {
							userid=str[1];
							Toast.makeText(RegisterActivity.this, "验证码已发送到您的手机，请查收", Toast.LENGTH_SHORT).show();
						}else if(str[0].equals("true_old")){
							Toast.makeText(RegisterActivity.this, "该手机用户已存在，请直接登录",
									Toast.LENGTH_SHORT).show();
							Intent i=new Intent(RegisterActivity.this,LoginActivity.class);
							RegisterActivity.this.startActivity(i);
							RegisterActivity.this.finish();
						}else{
							Toast.makeText(RegisterActivity.this, "获取验证码错误，请稍候重试",
									Toast.LENGTH_SHORT).show();
						}
					}catch (Exception e) {
						// TODO: handle exception
					
						Toast.makeText(RegisterActivity.this, "获取验证码错误，请稍候重试",
								Toast.LENGTH_SHORT).show();
					}
				}
			}
		};
		
		 mHandler = new Handler() {
		
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					if (mPositiveCount >= 2) {
						mPositiveCount--;
						if (bt_hqyzm != null) {
							bt_hqyzm.setText("重新获取(" + mPositiveCount + ")");
						}
						mHandler.sendEmptyMessageDelayed(1, 1000);
					} else {
						if (bt_hqyzm != null) {
							if (!bt_hqyzm.isEnabled()) {
								bt_hqyzm.setEnabled(true);
								bt_hqyzm.setBackgroundResource(R.drawable.ib_register_hqyzm_sel);
							/*	bt_hqyzm.setTextColor(getResources().getColor(R.color.white));
								bt_hqyzm.setText("获取验证码");*/
							
							}
						}
					}
					break;
				}
			}
		};
	    
	    commitHandler=new Handler()
		{
			public void handleMessage(Message msg)
			{
				super.handleMessage(msg);
				LoadDialog.closeDialog();
				
				if(msg.obj!=null && !msg.obj.toString().equals("")){
					String s=msg.obj.toString();
					
					if(s.equals("true")){
						uservo.setType(2);
						uservo.setId(Utils.str2int(userid));
						mApplication.saveUserVO(uservo);
						Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
						editor.putString("userid", userid);
						editor.commit();
						RegisterActivity.this.finish();
						Intent i = new Intent(ConstantData.Action.loginTag);
						RegisterActivity.this.sendBroadcast(i);
					}else if(s.equals("false")){
						Toast.makeText(RegisterActivity.this, "注册失败", Toast.LENGTH_SHORT).show();
					}else if(s.equals("vcodeerror")){
						Toast.makeText(RegisterActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
					}
				}else{
					Toast.makeText(RegisterActivity.this, "注册失败", Toast.LENGTH_SHORT).show();
				}
			}
		};
	}
	
}
